//
//  LTCurlRequestEx.cpp
//  LeTVCocos2d
//
//  Created by jeason on 16/7/25.
//  Copyright © 2016年 letv. All rights reserved.
//

#include "LTCurlRequestEx.h"
static std::set<LTCurlRequestEx *> requestList;
std::mutex mutexList;


LTCurlRequestEx::LTCurlRequestEx()
{
    operation = LTOperationManager::GetInstance()->CreateOperation();
}

LTCurlRequestEx::~LTCurlRequestEx()
{
    if (operation) {
        LTOperationManager::GetInstance()->DeleteOperation(operation);
    }
}



static void httpCallback(void *buffer,size_t datalength,bool success,void *context)
{
    if (!context) {
        return;
    }
    LTCurlRequestEx *requestEx = (LTCurlRequestEx*)context;
    requestEx->callbackFunction(buffer,datalength,success,
                                requestEx->operation->GetRequestID());
    
    {
        std::unique_lock <std::mutex> guard(mutexList);
        set<LTCurlRequestEx *>::iterator it = requestList.find(requestEx);
        if (it!=requestList.end()) {
            requestList.erase(it);
        }
    }
    
    if (requestEx) {
        delete requestEx;
        requestEx = nullptr;
    }
}

LTCurlRequestEx *LTCurlRequestEx::autoReleasedRequest()
{
    LTCurlRequestEx *ptr = new LTCurlRequestEx();
    {
        std::unique_lock <std::mutex> guard(mutexList);
        requestList.insert(ptr);
    }
    return ptr;
}



long LTCurlRequestEx::get(const char *url,
                          long timeout,
                          map<string, string> *header,
                          char *proxy,
                          void *context,
                          std::function<void(void*,size_t,bool, long)> callc)
{
    map<string, string> bakHeader;
    map<string, string> *newHeader = (header == NULL) ? (&bakHeader) : header;
    callbackFunction = callc;
    long urlLength      = 0;
    long proxyLength    = 0;
    if (url) {
        urlLength = strlen(url);
    }
    if (proxy) {
        proxyLength = strlen(proxy);
    }
    long requestId = operation->GetRequest(url, urlLength, timeout, *newHeader, this, proxy, proxyLength, httpCallback);
    LTOperationManager::GetInstance()->AddOperation(operation);
    return requestId;
}
